<?php
/**
 * Created by Sublime.
 * Author lingyun
 * Time:  2017-11-21 17:56:16
 */
namespace app\store\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use app\store\service\RefundService;
use app\comm\service\DadaOpenapi;

class Saleorder extends BasicAdmin{
	/**
	 * 订单列表页面
	 * Author   lingyun
	 * DateTime 2017-11-21T19:12:15+0800
	 * return   [type]                   [description]
	 */
	public function index(){
		$this->title = "线上订单列表";
		$get = $this->request->get();

		$store_id = session('user')['store_id'];

		$map = ['a.store_id'=>['eq',$store_id],'a.order_type'=>['eq',1]];
		$map1 = ['a.store_id'=>['eq',$store_id],'a.order_status'=>['eq',1],'a.order_type'=>['eq',1]];

		$join = [
			['ys_user b','b.uid=a.uid','LEFT'],
		];

		$db = Db::name('order')->alias('a')->join($join)->where($map)->field('a.*,b.realname,b.mobile')->order('a.id desc');

		$new_order = Db::name('order')->alias('a')->where($map1)->count();		//新订单的个数
		foreach (['order_sn'] as $key) {
			(isset($get[$key]) && $get[$key] !== '') && $db->whereLike('a.order_sn', "%{$get[$key]}%");
		}
		if(isset($get['date']) && $get['date'] !== '') {
			list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
			$start = $start."  00:00:00";		$end = $end." 23:59:59";
			$start = strtotime($start);			$end = strtotime($end);
			$db->whereBetween('a.addtime',["{$start}", "{$end}"]);
		}
		$this->assign('new_order',$new_order);		//新订单的个数
		return parent::_list($db);
	}

	/**
	 * 未处理订单列表
	 * Author   lingyun
	 * DateTime 2017-11-27T09:42:28+0800
	 * return   [type]                   [description]
	 */
	public function new_order(){
		$this->title = "未处理订单";
		$get = $this->request->get();
		$store_id = session('user')['store_id'];
		$join = [
			['ys_user b','b.uid=a.uid','LEFT'],
			['ys_order_details c','a.id=c.order_id','LEFT']
		];
		$db = Db::name('order')->alias('a')->join($join)->where(['a.store_id'=>$store_id,'a.order_status'=>1])->field('a.id,a.pay_type,a.pay_status,a.goods_num,a.final_amount,a.order_type,a.consignee,a.order_status,a.order_sn,b.realname,b.mobile,sum(c.is_tuihuo) as total,(select count(*) from ys_order_details where order_id=a.id ) as count')->order('a.id desc')->group('c.order_id');
		
		foreach (['order_sn'] as $key) {
			(isset($get[$key]) && $get[$key] !== '') && $db->whereLike('a.id', "%{$get[$key]}%");
		}
		if(isset($get['date']) && $get['date'] !== '') {
			list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
			$start = $start."  00:00:00";		$end = $end." 23:59:59";
			$start = strtotime($start);			$end = strtotime($end);
			$db->whereBetween('a.addtime',["{$start}", "{$end}"]);
		}
		return parent::_list($db);
	}

	/**
	 * 订单详情
	 * Author   lingyun
	 * DateTime 2017-11-22T08:41:43+0800
	 * return   [type]                   [description]
	 */
	public function detail(){
		$id = input('id');		//订单id   20171123.。。。。。
        $this->title = "订单详情";
		$join = [
			['ys_goods b', 'a.goods_id=b.id', 'LEFT'],
//			['ys_order c', 'a.id=c.id', 'LEFT'],
//			['ys_goods_spec_detail d', 'a.spec_id=d.id', 'LEFT']
		];
		//下单人信息以及订单信息
		$info = Db::name('order')->alias('c')->join('ys_user d', 'd.uid=c.uid', 'LEFT')->field('d.realname,d.mobile,d.uid,d.email,c.*')->where('c.id', $id)->find();

		//订单操作记录
		$action = Db::name('order_action')->alias('f')->join('ys_system_user e', 'f.action_user=e.id', 'LEFT')->field('f.*,e.username')->where('f.order_id', $id)->order('f.id asc')->select();        //订单action

		//订单商品详情
		$db = Db::name('order_details')->alias('a')->join($join)->where('a.order_id', $id)->field('a.*,a.goods_num anum,a.id aid,a.tuihuo_sign atuihuo,a.final_amount amount,b.name')->order('a.id desc');

		$this->assign('info',$info);
		$this->assign('action',$action);
		return parent::_list($db);
	}

	/**
	 * 退货原因
	 * Author   lingyun
	 * DateTime 2017-11-23T16:37:48+0800
	 * return   [type]                   [description]
	 */
	public function back(){
		$id = input('id');
		$info = Db::name('order_details')->alias('a')->join('goods b','a.goods_id=b.id','LEFT')->join('ys_order c','a.order_id=c.id','LEFT')->where('a.id',$id)->field('a.id,a.spec_detail,a.tuihuo_time,a.reason,a.img,a.tuihuo_sign,a.tuihuo_num,a.tuihuo_amount,a.th_deal_result,a.th_deal_remark,a.th_deal_time,b.name,c.id as order_id,c.pay_type,c.order_type')->find();
		$this->assign('info',$info);
		$this->assign('title','退货原因');
		return $this->fetch();
	}

	/**
	 * 调整价格
	 * Author   lingyun
	 * DateTime 2017-11-23T15:12:09+0800
	 * return   [type]                   [description]
	 */
	public function discount(){
		$table = "Order";
		return $this->_form($table,'discount');
	}

	/**
	 * 余额
	 * Author   lingyun
	 * DateTime 2017-11-23T16:05:51+0800
	 * return   [type]                   [description]
	 */
	public function refund(){
		if(request()->isPost()){
			$post = input('post.');				//接受的处理数据
			$service = new RefundService();		//服务层
			$order = Db::name('order_details')->alias('a')->join('ys_order b','a.order_id=b.id','LEFT')->where('a.id',$post['id'])->field('a.order_id,a.goods_id,a.spec_id,a.spec_detail,a.tuihuo_sign,a.give_score,a.tuihuo_num,a.tuihuo_amount,a.tuihuo_time,b.uid,b.pay_type,b.order_type,b.order_sn,b.pay_status,b.store_id')->find();
			if($order['pay_type'] == 3){				//余额支付，返回到余额
				$res = $service->refund_credit($order,$post);	//余额退款
				$res['code'] == 1?$this->success('退款成功',''):$this->error('退款失败','');
			}
		}else{
			$id = input('id');
			$info = Db::name('order_details')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where('a.id='.$id)->field('a.id,a.order_id,a.spec_id,a.spec_detail,a.goods_id,a.goods_num,a.give_score,a.tuihuo_sign,a.tuihuo_num,a.tuihuo_amount,a.tuihuo_time,b.name')->find();
			$this->assign('id',$id);
			$this->assign('info',$info);
			return $this->fetch('refund');
		}
	}

    /**
     * @Author lignyun
     * @Desc    发货处理
     */
	public function delivery(){
        $post = input('post.');
        $where_order['id'] = array('eq',$post['order_id']);
        //查询的订单
        $order =db('order')->where($where_order)->field('id,uid,store_id,consignee,mobile,address,city,final_amount,receiver_lng,receiver_lat')->find();
        $store = db('store')->where('id',$order['store_id'])->find();           //门店信息

        $store_code = sprintf("%04d", $post['store_id']);       //门店id
        $post['order_sn'] = $this->build_order_no().$store_code;
        $post['order_goods'] = implode(',',$post['order_goods']);
        //去掉’市‘，用于获取配送城市的编码
        $order['city'] = str_replace("市","",$order['city']);
        //获取配送城市的编码
        $city_arr = $this->get_city_code($order['city']);
        if($city_arr['code'] == 0){
            $this->error('配送城市不在允许的范围内','');
        }

        //达达配置信息
        $config_arr = config('dada');
//        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/addOrder";
        $config_arr['url'] = "http://newopen.imdada.cn/api/order/addOrder";             //线上域名
        $root = request()->domain();        //网站根目录
        $dada_obj = new DadaOpenapi($config_arr);

        $data_arr = array(
            'shop_no'=> $store['dada'],                 //门店编号，门店创建后可在门店列表和单页查看,此处为测试的账号
            'origin_id'=> $post['order_sn'],        //第三方订单ID
            'city_code'=> $city_arr['code'],        //城市编码
            'cargo_price'=> $order['final_amount'], //订单金额
            'is_prepay'=> 0,                        //是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
            'expected_fetch_time'=> time()+600,
            'receiver_name'=> $order['consignee'],
            'receiver_address'=> $order['address'],
            'receiver_phone'=> $order['mobile'],
            'receiver_tel'=> $order['mobile'],
            'receiver_lat'=> $order['receiver_lat'],
            'receiver_lng'=> $order['receiver_lng'],
            'callback'=>$root.'/index.php/index/dada/index',
//            'pay_for_supplier_fee'=> 0.0,
//            'fetch_from_receiver_fee'=> 0.0,
//            'deliver_fee'=> 0.0,
//            'tips'=> 0,
//            'info'=> '发货申请',
//            'cargo_type'=> 1,
//            'cargo_num'=> 2,
//            'expected_finish_time'=> 0,
//            'invoice_title'=> '发货申请',

        );
        $result = $dada_obj->makeRequest($data_arr);
        if (!$result) {
            //接口请求正常，判断接口返回的结果，自定义业务操作
            if ($dada_obj->getCode() == 0) {
                //配送订单信息
                $delivery_data_arr['store_id'] = $order['store_id'];
                $delivery_data_arr['order_id'] = $order['id'];
                $delivery_data_arr['order_sn'] = $post['order_sn'];
                $delivery_data_arr['order_goods'] = $post['order_goods'];
                $delivery_data_arr['create_time'] = time();
                $delivery_data_arr['update_time'] = time();
                $delivery_data_arr['order_status'] = 1;     //待接单
                //插入物流单数据
                $result = db('order_delivery')->data($delivery_data_arr)->insert();
                //更新商品发货状态
                $where['id'] = ['in',$post['order_goods']];
                $result = db('order_details')->where($where)->update(['status'=>3]);
                if($result>0){
                    $status = $this->check_delivery_status($post);      //检查订单是否已经全部发货
                    if($status == 1){       //已全部发货         未完待续。。。。。。
                        db('order')->where('id',$post['order_id'])->setField('order_status',3);
                        $action_arr = [
                            'uid'=>$order['uid'],
                            'order_id'=>$order['id'],
                            'action_user'=>session('user.id'),
                            'order_status'=>3,
                            'pay_status'=>1,
                            'status_desc'=>'订单已全部发货',
                            'storeid'=>$order['store_id'],
                            'addtime'=>time()
                        ];
                        db('order_action')->data($action_arr)->insert();        //记录订单动作状态
                    }else{
                        $action_arr = [
                            'uid'=>$order['uid'],
                            'order_id'=>$order['id'],
                            'action_user'=>session('user.id'),
                            'order_status'=>3,
                            'pay_status'=>1,
                            'status_desc'=>'订单已全部发货',
                            'storeid'=>$order['store_id'],
                            'addtime'=>time()
                        ];
                        db('order_action')->data($action_arr)->insert();        //记录订单动作状态
                    }
                }

                $result>0?$this->success('发货成功，等待取件！',''):$this->error('发货失败,请稍后再试！','');
            }else{
                $this->error($dada_obj->getMsg(),'');        //发货失败
            }
        }else{
            $this->error('网络异常，请稍后再试！','');        //发货失败
        }
    }

    /**
     * @Author  lingyun
     * @Desc    模拟发货单的最新的订单状态
     * @param $param
     */
    public function delivery_order_action(){
        $config_arr = config('dada');
//        $config_arr['url'] = "http://newopen.imdada.cn/api/order/accept";                //模拟接受订单 3
//        $config_arr['url'] = "http://newopen.imdada.cn/api/order/fetch";                 //模拟完成取货
//        $config_arr['url'] = "http://newopen.imdada.cn/api/order/finish";                //模拟完成订单
//        $config_arr['url'] = "http://newopen.imdada.cn/api/order/cancel";                  //模拟取消订单
//        $config_arr['url'] = "http://newopen.imdada.cn/api/order/expire";                //模拟订单过期
        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/status/query";          //订单详情查询
        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr['order_id'] = '20180507082606101535750013';
        $result = $dada_obj->makeRequest($data_arr);
        if(!$result){
//            $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/status/query";
            $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/status/query";
            $dada_obj = new DadaOpenapi($config_arr);
            $data_arr['order_id'] = '20180507082606101535750013';
            $result = $dada_obj->makeRequest($data_arr);
//            if(!empty($result)){
                echo $dada_obj->getCode();
                echo $dada_obj->getStatus();
                echo $dada_obj->getMsg();
                halt($dada_obj->getResult());
//            }


        }
        halt($result);
    }

    /**
     * @Author  lingyun
     * @Desc    检查是否全部发货
     * @return int   1全部发货，0未全部发货
     *
     */
    private function check_delivery_status($param){
        $status = 1;        //全部发货状态
        //订单详情
        $map = [
            'order_id'=>['eq',$param['order_id']],
            'id'=>['not in',$param['order_goods']]
        ];
        $order = db('order_details')->where($map)->field('id,goods_id,status')->select();           //找到其他的订单商品判断是否已经发货
        if(!empty($order)){
            foreach($order as $k => $v){
                if($v['status'] != 3){
                    $status = 0;        //未全部发货
                    break;
                }
            }
        }
        return $status;
    }

    /**
     * @Author  lignyun
     * @Desc    获取配送城市编码
     * @param   $city[string]   配送的城市
     * @return  array      返回匹配的结果
     */
    public function get_city_code($city){
        $config_arr = config('dada');
//        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/cityCode/list";
        $config_arr['url'] = "http://newopen.imdada.cn/api/cityCode/list";

        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr = array('body'=>'');
        $result = $dada_obj->getCity($data_arr);
        $result = json_decode($result,true);
        //请求成功
        if($result['code'] == 0){
            //支持城市列表
            $city_arr = $result['result'];
            $result = array_filter($city_arr, function($t) use ($city) { return $t['cityName'] == $city; });
            $result = array_values($result);
            if(!empty($result)){
                return ['code'=>1,'city_code'=>$result[0]['cityCode']];
            }else{
                return ['code'=>1,'city_code'=>'配送城市不在允许的范围内'];
            }
        }else{      //请求失败
            return ['code'=>0,'city_code'=>'请求失败'];
        }
    }

    /**
     * 生成唯一的订单号
     * @return string
     */
    private function build_order_no()
    {
        return date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


}